<template>
	<view>
		<view class="no-list" v-if="is_init">

		</view>
		<!-- <view class="no-list" v-else-if="!is_login" @click="toLogin()">
			登录后可查看交流平台
		</view> -->
		<view class="no-list" v-else-if="!has_quan">
			暂无权限
		</view>
		<!-- <view class="no-list" v-else-if="!is_open">
			已关店
		</view> -->
		<view class="list" v-else>
			<view class="no-list" style="padding: 13rpx 30rpx;">信息发布</view>
			<view class="flex_col" @longpress="onLongPress" :class="{'active':pickerUserIndex==index}"
				v-for="(item,index) in userList" :key="index" :data-index="index"
				@click="toPage(`./index?room_id=${item.room_id || ''}&area_id=${item.area_id || ''}`)"
				v-if="!item.area_id">
				<view class="imgbox">
					<image :src="siteConf.logo" mode="aspectFill"></image>
					<text v-if="item.unread>0">{{item.unread}}</text>
				</view>
				<view class="flex_grow">
					<view class="flex_col">
						<view class="flex_grow">{{item.room_name}}</view>
						<view class="time">{{item.time || item.room.create_time}}</view>
					</view>
					<view class="info">{{item.info || ''}}</view>
				</view>
			</view>
			<view class="no-list" style="padding: 13rpx 30rpx;">以下为各地区信息查看</view>
			<view class="flex_col" @longpress="onLongPress" :class="{'active':pickerUserIndex==index}"
				v-for="(item,index) in userList" :key="index" :data-index="index"
				@click="toPage(`./index?room_id=${item.room_id || ''}&area_id=${item.area_id || ''}`)"
				v-if="item.area_id">
				<view class="imgbox">
					<image :src="siteConf.logo" mode="aspectFill"></image>
					<text v-if="item.unread>0">{{item.unread}}</text>
				</view>
				<view class="flex_grow">
					<view class="flex_col">
						<view class="flex_grow">{{item.room_name}}</view>
						<view class="time">{{item.time || item.room.create_time}}</view>
					</view>
					<view class="info">{{item.info || ''}}</view>
				</view>
			</view>
		</view>
		<view class="shade" v-show="showShade" @tap="hidePop">
			<view class="pop" :style="popStyle" :class="{'show':showPop}">
				<view v-for="(item,index) in popButton" :key="index" @tap="pickerMenu" :data-index="index">{{item}}
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		UserInfo
	} from "@/api/api.js"
	import {
		getStoreChatRoom
	} from "@/api/user.js"
	import {
		getChatRoom
	} from "@/api/chat.js"
	export default {
		data() {
			return {
				is_init: true,
				userList: [],
				/* 窗口尺寸 */
				winSize: {},
				/* 显示遮罩 */
				showShade: false,
				/* 显示操作弹窗 */
				showPop: false,
				/* 弹窗按钮列表 */
				popButton: ["标为关注", "置顶聊天", "删除该聊天"],
				/* 弹窗定位样式 */
				popStyle: "",
				/* 选择的用户下标 */
				pickerUserIndex: -1,
				websocket_url: '',
				user_id: '',
				is_login: false,
				has_quan: false,
				is_open: true,
				is_connect: false

			}
		},
		onLoad() {
			// this.getListData();
			this.getWindowSize();

			// #ifdef H5
			document.onLong = function(e) {
				var e = e || window.event;
				e.preventDefault();
			};
			// #endif
		},
		onNavigationBarButtonTap(e) {
			uni.navigateTo({
				url: '/shoper/user/chat/choose-area'
			})
		},
		onUnload() {
			this.is_connect && uni.closeSocket({
				complete: () => {
					console.log('卸载socket');
				}
			})
		},
		async onShow() {
			let that = this
			let reqRes = await UserInfo()
			this.is_init = false
			let reqData = reqRes.data
			if (!reqData.user) {
				this.is_login = false
				this.$store.dispatch('clearState')
				// return false
				this.user_id = this.generateUUID()
			} else {
				this.user_id = reqData.user_id
				this.is_login = true
			}
			let chatRes = await getChatRoom()
			if (chatRes.code == 501) {
				//需要选择身份
				const pages = getCurrentPages()
				const currentPage = pages[pages.length - 1]
				uni.redirectTo({
					url: '/pages/user/role?redirect=' + encodeURIComponent(currentPage.route)
				})
				return false
			}
			if (chatRes.code == 403) {
				//需要选择身份
				this.has_quan = false
				return false
			}
			if (chatRes.code != 0) {
				//其他错误
				this.$store.dispatch('clearState')
				return false
			}
			this.userList = chatRes.data
			// if (!reqData.is_store) {
			// 	this.has_quan = false
			// 	return false
			// }
			this.has_quan = true
			// if (!reqData.is_open) {
			// 	this.is_open = false
			// 	return false
			// }
			// this.is_open = true
			// if (!reqData.room_id) {
			// 	uni.redirectTo({
			// 		url: '/shoper/user/chat/choose-area'
			// 	})
			// 	return
			// }
			this.websocket_url = reqData.websocket
			if (!this.is_connect) {
				this.webSocket()
			}
			// this.getChatRoom()
		},
		methods: {
			webSocket() {
				var that = this
				if (that.is_connect) {
					return false
				}
				// uni.showLoading({
				// 	title: '连接房间。。。'
				// })
				this.socketTask = uni.connectSocket({
					// url: 'wss://www.example.com/socket',
					url: `${that.websocket_url}?&user_id=${that.user_id}`,
					success: (suc) => {
						console.log('suc', suc);
					},
					fail: (err) => {
						console.log('err', err);
					},
					complete: (data) => {
						console.log('complete', data);
					}
				});
				this.socketTask.onOpen(function(res) {
					uni.hideLoading()
					console.log('WebSocket连接已打开！');
					that.is_connect = true
				});
				this.socketTask.onError(function(res) {
					that.is_connect = false
					console.log('WebSocket连接打开失败，请检查！');
					that.fail_count++
					if (that.fail_count <= 7) {
						// uni.showLoading({
						// 	title: '重新连接。。。'
						// })
						that.webSocket()
					}

				});
				this.socketTask.onClose(function(res) {
					that.is_connect = false
					console.log('WebSocket 已关闭！');
				});
				this.socketTask.onMessage(function(res) {
					let data = JSON.parse(res.data)
					console.log('收到服务器内容：', data, that.is_connect);
					if (data.type == 'ping') {
						return
					}
					if (data.code == 0) {
						let content = data.content
						if (data.type == 'tips') {
							//未读加1
							let content = data.content
							let index = that.userList.findIndex(item => item.room_id == content.room_id)
							if (index >= 0) {
								that.userList[index].unread = that.userList[index].unread + 1
								that.userList[index].info = content.type == 1 ? content.content.content : '[图片]'
							}
						}
					} else {
						uni.$showMsg(data.msg || '接收失败')
					}

				});
			},
			toLogin() {
				// #ifdef H5
				uni.navigateTo({
					url: '/pages/login/index'
				})
				// #endif
				// #ifdef MP-WEIXIN
				uni.navigateTo({
					url: '/pages/login/login'
				})
				// #endif
			},
			getStoreChatRoom() {
				getStoreChatRoom().then(res => {
					if (res.code == 0) {
						this.userList = res.data
						if (!this.is_connect) {
							this.webSocket()
						}
					}
				})
			},
			/* 列表触摸事件 */
			listTap() {
				/* 因弹出遮罩问题，所以需要在遮罩弹出的情况下阻止列表事件的触发 */
				if (this.showShade) {
					return;
				}

				console.log("列表触摸事件触发")
			},
			/* 获取列表数据 */
			// getListData() {
			// 	let list = [];
			// 	for (let i = 0; i < 20; i++) {
			// 		list.push({
			// 			"name": `第${i+1}个用户`,
			// 			"time": '5月20日',
			// 			"info": `这是第${i+1}个用户的聊天信息`
			// 		})
			// 	}
			// 	this.userList = list;
			// },
			/* 获取窗口尺寸 */
			getWindowSize() {
				uni.getSystemInfo({
					success: (res) => {
						this.winSize = {
							"witdh": res.windowWidth,
							"height": res.windowHeight
						}
					}
				})
			},
			/* 长按监听 */
			onLongPress(e) {
				return
				let [touches, style, index] = [e.touches[0], "", e.currentTarget.dataset.index];

				/* 因 非H5端不兼容 style 属性绑定 Object ，所以拼接字符 */
				if (touches.clientY > (this.winSize.height / 2)) {
					style = `bottom:${this.winSize.height-touches.clientY}px;`;
				} else {
					style = `top:${touches.clientY}px;`;
				}
				if (touches.clientX > (this.winSize.witdh / 2)) {
					style += `right:${this.winSize.witdh-touches.clientX}px`;
				} else {
					style += `left:${touches.clientX}px`;
				}

				this.popStyle = style;
				this.pickerUserIndex = Number(index);
				this.showShade = true;
				this.$nextTick(() => {
					setTimeout(() => {
						this.showPop = true;
					}, 10);
				});
			},
			/* 隐藏弹窗 */
			hidePop() {
				this.showPop = false;
				this.pickerUserIndex = -1;
				setTimeout(() => {
					this.showShade = false;
				}, 250);
			},
			/* 选择菜单 */
			pickerMenu(e) {
				let index = Number(e.currentTarget.dataset.index);
				console.log(`第${this.pickerUserIndex+1}个用户,第${index+1}个按钮`);
				// 在这里开启你的代码秀

				uni.showToast({
					title: `第${this.pickerUserIndex+1}个用户,第${index+1}个按钮`,
					icon: "none",
					mask: true,
					duration: 600
				});

				/* 
				 因为隐藏弹窗方法中会将当前选择的用户下标还原为-1,
				 如果行的菜单方法存在异步情况，请在隐藏之前将该值保存，或通过参数传入异步函数中
				 */
				this.hidePop();
			}
		}
	}
</script>

<style scoped lang="scss">
	/* 列式弹性盒子 */
	.flex_col {
		display: flex;
		flex-direction: row;
		flex-wrap: nowrap;
		justify-content: flex-start;
		align-items: center;
		align-content: center;

		.imgbox {
			position: relative;

			text {
				color: #fff;
				background: #f00;
				border-radius: 50%;
				width: 24px;
				height: 24px;
				position: absolute;
				top: 0px;
				right: 5px;
				font-size: 12px;
				display: flex;
				align-items: center;
				justify-content: center;
				transform: scale(.75);
			}
		}
	}

	/* 弹性盒子弹性容器 */
	.flex_col .flex_grow {
		width: 0;
		-webkit-box-flex: 1;
		-ms-flex-positive: 1;
		flex-grow: 1;
	}

	.flex_row .flex_grow {
		-webkit-box-flex: 1;
		-ms-flex-positive: 1;
		flex-grow: 1;
	}

	/* 弹性盒子允许换行 */
	.flex_col.flex_wrap {
		-ms-flex-wrap: wrap;
		flex-wrap: wrap;
	}

	/* 列表 */
	.list {
		background-color: #fff;
		font-size: 28upx;
		color: #333;
		user-select: none;
		touch-callout: none;

		&>view {
			padding: 24upx 30upx;
			position: relative;

			&:active,
			&.active {
				background-color: #f3f3f3;
			}

			image {
				height: 80upx;
				width: 80upx;
				border-radius: 4px;
				margin-right: 20upx;
			}

			&>view {
				line-height: 40upx;

				.time,
				.info {
					color: #999;
					font-size: 24upx;
				}

				.time {
					text-align: right;
				}

				.info {
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
			}
		}

		&>view:not(:first-child) {
			margin-top: 1px;

			&::after {
				content: '';
				display: block;
				height: 0;
				border-top: #CCC solid 1px;
				width: 620upx;
				position: absolute;
				top: -1px;
				right: 0;
				transform: scaleY(0.5);
				/* 1px像素 */
			}
		}
	}

	/* 遮罩 */
	.shade {
		position: fixed;
		z-index: 100;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		-webkit-touch-callout: none;

		.pop {
			position: fixed;
			z-index: 101;
			width: 200upx;
			box-sizing: border-box;
			font-size: 28upx;
			text-align: left;
			color: #333;
			background-color: #fff;
			box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
			line-height: 80upx;
			transition: transform 0.15s ease-in-out 0s;
			user-select: none;
			-webkit-touch-callout: none;
			transform: scale(0, 0);

			&.show {
				transform: scale(1, 1);
			}

			&>view {
				padding: 0 20upx;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				user-select: none;
				-webkit-touch-callout: none;

				&:active {
					background-color: #f3f3f3;
				}
			}
		}
	}
</style>